package com.pb.wkflow.core.listener;

import com.pb.infra.oth.util.SpringContextUtil;
import com.pb.wkflow.api.service.WfSysProcInfoService;
import com.pb.wkflow.core.config.Constants;
import com.pb.wkflow.core.config.DeleteReasonConstants;
import com.pb.wkflow.core.utils.StringUtils;
import com.pb.wkflow.core.utils.WorkflowThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.history.event.HistoricTaskInstanceEventEntity;

/**
 * @author 苗益辉
 * @date 2022/9/26 14:00
 */
@Slf4j
public class ExecutionEndListener implements ExecutionListener {

    @Override
    public void notify(DelegateExecution execution) {
        log.info("------------ 事件结束监听 ------------");
        WfSysProcInfoService wfSysProcInfoService = SpringContextUtil.getBean(WfSysProcInfoService.class);
        //设置任务状态
        String deleteReasonProcInstId = WorkflowThreadLocalUtil.getString("deleteReasonProcInstId");
        String deleteReasonTaskId = WorkflowThreadLocalUtil.getString("deleteReasonTaskId");
        String deleteReason = WorkflowThreadLocalUtil.getString("deleteReason");
        if (StringUtils.isNotBlank(deleteReason) && StringUtils.isNotBlank(deleteReasonTaskId)) {
            HistoricTaskInstanceEventEntity historicTaskInstanceEventEntity = Context.getCommandContext().getDbEntityManager()
                    .getDbEntityCache().get(HistoricTaskInstanceEventEntity.class, deleteReasonTaskId);
            if (historicTaskInstanceEventEntity != null) {
                historicTaskInstanceEventEntity.setDeleteReason(deleteReason);
            }
        }
        if (StringUtils.isNotBlank(deleteReasonProcInstId)) {
            wfSysProcInfoService.update(deleteReasonProcInstId, deleteReason, null, Constants.Flag.FALSE);
        }
    }
}
